﻿using EYWeb.Core;
using EYWeb.Domain.Entities;
using EYWeb.Repositories;
using System;

namespace EYWeb.Services
{
    public class UserService : BaseService<UserEntity>, IUserService
    {
        private readonly IUserRepository _userRepository;
        private readonly IUserLogOnRepository _userLogOnRepository;

        public UserService(IUserRepository userRepository, IUserLogOnRepository userLogOnRepository) : base(userRepository)
        {
            _userRepository = userRepository;
            _userLogOnRepository = userLogOnRepository;
        }

        public UserEntity CheckLogin(string user, string pass)
        {
            UserEntity userEntity = _userRepository.FindByClause(t => t.Account == user);
            if (userEntity != null)
            {
                if (userEntity.EnabledMark == true)
                {
                    UserLogOnEntity userLogOnEntity = _userLogOnRepository.FindById(userEntity.Id);
                    string dbPass = Md5.md5(DESEncrypt.Encrypt(pass.ToLower(), userLogOnEntity.UserSecretkey).ToLower(), 32).ToLower();
                    if (dbPass == userLogOnEntity.UserPassword)
                    {
                        userLogOnEntity.LogOnCount = (userLogOnEntity.LogOnCount).ToInt() + 1;
                        if (userLogOnEntity.LastVisitTime != null)
                        {
                            userLogOnEntity.PreviousVisitTime = userLogOnEntity.LastVisitTime;
                        }
                        userLogOnEntity.LastVisitTime = DateTime.Now;
                        _userLogOnRepository.Update(userLogOnEntity);
                        return userEntity;
                    }
                    else
                    {
                        throw new Exception("密码不正确,请重新输入.");
                    }

                }
                else
                {
                    throw new Exception("账户被系统锁定,请联系管理员.");
                }
            }
            else
            {
                throw new Exception("账户不存在,请重新输入.");
            }

        }

        public UserEntity FindByLoginName(string loginName)
        {
            return _userRepository.FindByClause(x => x.Account == loginName);
        }
    }
}
